/**
 * Created by mooshroom on 2015/8/1 0001.
 *
 * 客户供应商管理模块
 *
 * css共用商品模块的样式
 */
define('customer', [
    'avalon',
    'text!../../package/customer/customer.html',
    'text!../../package/customer/info.html',
    'css!../../package/goods/goods.css',
    'css!../../package/customer/customer.css'
], function (avalon, html,info) {
    var vm = avalon.define({
        $id: "customer",
        ready: function (id) {
            layout.url = html;
            if (id) {
                vm.cusId = id
            }
            else {
                vm.cusId = ""
            }

            if (vm.firstTime) {
                setTimeout(function () {
                    vm.getCus()
                }, 1)

                vm.firstTime = false
            }

            avalon.scan();
        },
        firstTime: true,
        /*显示控制*/
        showBtn: -2,
        showThisBtn: function (i) {
            vm.showBtn = i
        },
        hideThisBtn: function (i) {
            vm.showBtn = -2
        },


        /*控制列表渲染*/
        list: [],

        cusId: "",//客户ID，用户查看详情，详情与列表的切换也是根据这个值，
        P: 0,
        T: 0,
        //获取客户列表
        getCus: function () {
            ws.call({
                i: "Customer/get",
                data: {
                    CustomerIDs: [],
                    P: vm.P + 1,
                    N: 48
                },
                success: function (res) {
                    if(!res.err){
                        vm.P = res.P
                        vm.T = res.T
                        if(res.L!=null){
                            for (var i = 0; i < res.L.length; i++) {
                                vm.list.push(res.L[i])
                            }
                        }
                        else{
                            vm.P=res.P-1
                            tip.on('没有更多数据了……',1,3000)
                        }

                    }
                    else{
                        console.log(res)
                    }

                }
            })
        },

        //添加
        New: {
            Name: "",
            Type: 0,
            "Address": "",
            "Phone": "",
            Payable:0,
            Receivables:0
        },
        add: function () {
            //todo 这里添加表单的验证

            if (vm.New.Name != "") {
                ws.call({
                        i: "Customer/add",
                        data: {
                            'Name': vm.New.Name,//单位名称
                            'Receivables': vm.New.Receivables,//期初应收账款
                            'Payable': vm.New.Payable,//期初应付账款
                            'Address': vm.New.Address,//地址
//                                'Memo': vm.New.Name,//备注
                            'Type': vm.New.Type,//单位类型 0 客户，1：供应商
                            'On': 1,//是否开启
                            'Phone': vm.New.Phone//电话
//                                'LandLine': vm.New.Name,//座机
//                                'QQ': vm.New.Name//qq
                        },
                        success: function (res) {


                            vm.addOver()
                            //构建新商品插入列表
                            ws.call({
                                i: "Customer/get",
                                data: {
                                    CustomerIDs: [res.CustomerID],
                                    P: 1,
                                    N: 30
                                },
                                success: function (res) {
                                    if (res.L.length) {
                                        vm.list.unshift(res.L[0])
                                        vm.New={
                                            Name: "",
                                            Type: 0,
                                            "Address": "",
                                            "Phone": "",
                                            Payable:0,
                                            Receivables:0
                                        }
                                    }
                                }
                            })


                        }
                    }
                )
            }
            else {
                tip.on('您还没有输入名称！！！')
            }

        },
        //取消添加
        addOver: function () {
            vm.New = {
                Name: "",
                Type: 0,
                "Address": "",
                "Phone": ""
            }
            vm.editClose()
        },


//编辑
        befor: {
        },
        editing: -2,
        edit: function (i) {
            //先滚回上一个在编辑的商品
            vm.editClose()
//            vm.befor={}

            //然后进行正常的编辑动作

            vm.editing = i
//            vm.befor=vm.list[i]
            var poto = vm.list[i]
            var x;
            for (x in poto) {
                if (x.charAt(0) != '$') {
                    vm.befor[x] = poto[x]
                }
            }

        },
        editClose: function () {
            //撤销修改
            if (vm.editing != -2) {
                var poto = vm.befor
                var x;
                for (x in poto) {
                    if (x.charAt(0) != '$') {
                        if (vm.editing != -7) {
                            try{
                                //在列表修改
                                vm.list[vm.editing][x] = poto[x]
                            }
                            catch (err){

                            }

                        }
                    }
                }
            }


//            重置当前编辑索引
            vm.editing = -2
        },

//编辑任务身份
        editType: function (index, type) {
            var t;
            if (index == -1) {
                t = vm.New
            }
            else if(index==-2){
                t=vm.info
            }
            else {
                t = vm.list[index]
            }

            if (t.Type == 0) {
                //当前为客户
                if (type == 1) {
                    t.Type = 2
                }
            }
            else if (t.Type == 1) {
                //当前为供应商
                if (type == 0) {
                    t.Type = 2
                }
            }
            else {
                //两者都是
                if (type == 0) {
                    t.Type = 1
                } else if (type == 1) {
                    t.Type = 0
                }
            }
        },
//保存更改
        save: function (i) {


            var after = vm.list[i]

            if (after.Name != '') {
                var befor = vm.befor
                var r2s = {}
                //先判断哪些属性变化了
                var x;
                for (x in after) {
                    if (x != "Price" && x.charAt(0) != '$') {
                        if (after[x] != befor[x]) {
                            //记录变化的属性
                            r2s[x] = after[x]
                        }
                    }
                }

                //发起保存
                ws.call({
                    i: "Customer/save",
                    data: {
                        CustomerID: after.CustomerID,
                        Param: r2s
                    },
                    success: function (res) {
                        if (res.err == undefined) {
                            tip.on('保存成功', 1, 3000)
                            vm.befor = after
                            vm.editClose()
                        }
                    }
                })

            }
            else {
                tip.on('名字被吃掉啦！')
                vm.list[i].Name = vm.befor.Name
            }
        },


        /*详情所用*/
        CusID:"",
        toInfo: function (i,edit) {
            window.location.href="#!/customerInfo/"+i

            if(edit===1){
                //进入编辑状态
                setTimeout(function(){
                    vm.infoEdit(vm.info.CustomerID)
                },300)

            }
        },
        info:{},
        infoReady:function(id){
            vm.infoReset()

            vm.CusID=id
            layout.url=info
            ws.call({
                i:"Customer/get",
                data:{
                    CustomerIDs:[id],
                    P:1,
                    N:100

                },
                success:function(res){
                    if(res.L.length){
                        vm.info={}
                        vm.buildInfo(res.L[0])
                        vm.updateList(res.L[0])
                        quickStart.goOut()
                        vm.getOrder()
                    }
                }
            })

        },
        updateList:function(obj){
            for (var k = 0; k < vm.list.length; k++) {
                if (vm.list[k].CustomerID == obj.CustomerID) {
                    //找到更新的数据
                    var target = vm.list[k], x;
                    for (x in obj) {
                        if (x.charAt(0) != '$') {
                            target[x] = obj[x]
                        }
                    }

                    break
                }
            }
        },
        infoReset: function () {
            vm.CusID='';
            vm.info={};
            vm.OrderList=[];
            vm.lP=0;
            vm.lT=0;
            vm.pay=0
            vm.income=0;
            vm.pay2=0
            vm.income2=0;
            vm.moneyInput=0;
            vm.editing=-2;
            vm.allChecked=false
            try{
                vm.settleAddUp()
            }catch(err){console.log(err)}
        },
        buildInfo: function (obj) {
            var poto=obj
            var x;
            var a={};
            for(x in poto){
                if(x.charAt(0)!='$'){
                    a[x]=poto[x]
                }
            }
            vm.info=a

        },

        //在详情页编辑
        infoEdit: function (id) {

            vm.editing=-7;
            var poto=vm.info
            var x;
            for(x in poto){
                if(x.charAt(0)!='$'){
                    vm.befor[x]=poto[x]
                }
            }
        },

        //保存（在详情）
        infoSave: function () {
            var after=vm.info

            if(after.Name!=''){
                var befor=vm.befor
                var r2s={}
                //先判断哪些属性变化了
                var x;
                for(x in after){
                    if(x!="Price"&& x.charAt(0)!='$'){
                        if(after[x]!=befor[x]){
                            //记录变化的属性
                            r2s[x]=after[x]
                        }
                    }
                }
                function reload() {
                    vm.infoReady(after.CustomerID)
                }

                setTimeout(function(){
                    //发起保存
                    ws.call({
                        i:"Customer/save",
                        data:{
                            CustomerID:after.CustomerID,
                            Param:r2s
                        },
                        success:function (res){
                            if(res.err==undefined){
                                tip.on('保存成功',1,3000)
                                reload()

                            }
                        }
                    })
                },1)
                vm.editClose()
            }
            else{
                tip.on('商品名被吃掉啦！')
                vm.info.Name=vm.befor.Name
            }
        },

        //获取与该客户的订单
        OrderList:[],
        lP:0,
        lT:0,
        getOrder: function () {
            ws.call({
                i:"Order/search",
                data:{
                    P:vm.lP+1,
                    N:24,
                    W:{
                        CustomerID:vm.CusID,
                        //OrderCode:["in","-1,-2,1,2,3,-3"]
                    },
                    Clear:2
                },
                success: function (res) {
                    if(!res.err){
                        vm.lP=res.P;
                        vm.lT=res.T;
                        if(res.L.length>0){
                            for(var i=0;i<res.L.length;i++){
                                res.L[i].Need=(Number(res.L[i].Total)-Number(res.L[i].Payed)).toFixed(2)
                                res.L[i].checkable=true
                                vm.OrderList.push(res.L[i])

                            }
                        }else{
                            tip.on('没有更多订单了……',1,3000)
                            vm.lP=res.P-1
                        }

                    }
                    else{
                        console.log(res)
                    }
                }

            })
        },

        //查看订单详情
        ready2info: function () {
            require(['../../package/Order/info'], function () {

            })
        },
        changeing:'',//标记正在被改变的详情
        toOrderInfo: function (id,index,OrderCode) {
            if(Math.abs(OrderCode)!=3){
                window.location.href='#!/OrderInfo/'+id
                vm.changeing=index
            }
        },
        
        //更新相关数据
        uploadMoney: function (money) {
            //更新列表项目
            vm.OrderList[vm.changeing].Payed=(Number(vm.OrderList[vm.changeing].Payed)+Number(money)).toFixed(2)
            vm.OrderList[vm.changeing].Need=(Number(vm.OrderList[vm.changeing].Need)-Number(money)).toFixed(2)

            //更新总共的
            if(vm.OrderList[vm.changeing].OrderCode>0){
                //付款
                vm.info.Payable=vm.info.Payable-money
            }
            else if(vm.OrderList[vm.changeing].OrderCode<0){
                //收款
                vm.info.Receivables=vm.info.Receivables-money
            }
        },

        /*收付款（按客户）*/
        moneyInput:0,
        showInput: function (i) {
            vm.moneyInput=i
        },
        pay:0,
        income:0,
        pushMoney:function(){
            if(vm.moneyInput==1){

                if(Number(vm.pay)<=0){
                    tip.on('结算金额必须大于0')
                }
                else if(Number(vm.pay)>Number(vm.info.Payable)){
                    tip.on('结算金额超出了所需要结算的额度')
                    //if(confirm("您将要支付的金额超过未结算的金额，多余的金额将不会被计算，是否继续？")){
                    //    push(-vm.pay)
                    //}
                }
                else if(isIt.money(vm.pay,"结算金额")){
                    //付款
                    if(isIt.money(vm.pay,"所输入的金额")){

                        vm.OrderSettle(-vm.pay)
                    }
                }

            }
            else if(vm.moneyInput==2){
                if(Number(vm.income)<=0){
                    tip.on('结算金额必须大于0')
                }
                else if(Number(vm.income)>Number(vm.info.Receivables)){
                    tip.on('您将要收取的金额超过未结算的金额')
                    //if(confirm("您将要收取的金额超过未结算的金额，多余的金额将不会被计算，是否继续？")){
                    //    push(vm.income)
                    //}
                }
                else{
                    //付款
                    if(isIt.money(vm.income,"想要收取的金额")){

                        vm.OrderSettle(vm.income)
                    }
                }
            }


        },
        OrderSettle:function(money,OrderIDs){
            var data={
                CustomerID:vm.CusID,
                Money:money
            }
            if(OrderIDs!=undefined&&typeof(OrderIDs)=="object"){
                data.OrderIDs=OrderIDs
            }
            else if(typeof(OrderIDs)!="object"){
                console.log("!!!!!!!!!!!!!!!!!!!!!传入参数错误：!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
                console.log(OrderIDs)
            }
            ws.call({
                i:'Order/settle',
                data:data,
                success: function (res) {
                    if(!res.err){
                        var id=vm.CusID
                        vm.infoReset()
                        vm.infoReady(id)
                    }
                    else{
                        console.log(res)
                    }
                }
            })
        },

        /*收付款（按选中订单）*/
        pay2:0,
        income2:0,
        //选中
        check:function(index){
            vm.OrderList[index].checkable=!vm.OrderList[index].checkable
            vm.settleAddUp()
        },

        //选中全部
        allChecked:false,
        checkAll:function(){
            var list=vm.OrderList
            var tf;
            if(vm.allChecked){
                //全部取消选择
                vm.allChecked=false
                    tf=true
            }
            else{
                //全部选中
                vm.allChecked=true
                    tf=false
            }
            for(var i= 0;i<list.length;i++){
                list[i].checkable=tf
            }
            vm.settleAddUp()
        },

        //反选
        checkToggle:function(){
            var list=vm.OrderList
            for(var i= 0;i<list.length;i++){
                list[i].checkable=!list[i].checkable
            }
            vm.settleAddUp()
            vm.allChecked=false
        },

        //需结算金额计算
        allInM:0.00,
        allOutM:0.00,
        $checkedOrderS:{
            inM:[],
            outM:[]
        },
        settleAddUp:function(){
            var list=vm.OrderList
            var allInM= 0,
                allOutM= 0,
                inM="",
                outM="";
            for(var i= 0;i<list.length;i++){
                if(!list[i].checkable&&list[i].Need!=0){
                    //被选中的
                    if(list[i].OrderCode>0){
                        //要给钱的入库单
                        allOutM+=Math.abs(list[i].Need)
                        //outM.push(list[i].OrderID)
                        if(outM===""){
                            outM=list[i].OrderID
                        }else{
                            outM+=","+list[i].OrderID
                        }

                    }else if(list[i].OrderCode<0){
                        //要收款的出库单
                        allInM+=Math.abs(list[i].Need)
                        console.log(allInM)
                        if(inM===""){
                            inM=list[i].OrderID
                        }else{
                            inM+=","+list[i].OrderID
                        }
                    }
                }
            }
            function resArr(str){
                if(str===""){
                    return []
                }else{
                    return str.split(",")
                }
            }
            vm.allInM=allInM.toFixed(2)
            if(vm.allInM==0){
                vm.income2=0
            }
            vm.allOutM=allOutM.toFixed(2)
            if(vm.allOutM==0){
                vm.pay2=0
            }
            vm.$checkedOrderS={
                inM:resArr(inM),
                outM:resArr(outM),
            }
            console.log(vm.$checkedOrderS)
        },

        //执行结算动作
        settleCheckedOrders:function(){
            var pay2=vm.pay2,income2=vm.income2;
            if(Number(pay2)==Number(vm.allOutM)&&Number(income2)==Number(vm.allInM)){
                //金额是输入正确的
                if(pay2>0){
                    vm.OrderSettle(-pay2,vm.$checkedOrderS.outM)
                }

                if(income2>0){
                    vm.OrderSettle(income2,vm.$checkedOrderS.inM)
                }

            }
            else{
                tip.on("结算的金额需要与待结算的金额一致")
            }

        }



    })
    return customer = vm
})